<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2017/7/14
 * Time: 0:06
 */

namespace logic\admin\index;



use library\common\arr;
use library\tencent\wechat\wechat_index\PayManagement;
use library\tencent\wechat\wechat_index\SdkConfig;
use model\Account;
use model\AccountBill;
use model\AccountLog;
use model\AccountWithdrawOrder;
use think\Config;
use think\Db;
use think\Request;

class LAccountWithdrawOrder
{
    public function logic_index_data($status,$params){
        $model = new AccountWithdrawOrder();
        $where=array();
        if (!empty($keywords)) {
            $where['w.order_sn|a.name|a.mobile|a.wechat'] = array('like', "%{$keywords}%"); //查询条件
        }

        $status_id = $status;

        if($status_id == 2){
            $where['flag_status'] = 0;
        }

        // <editor-fold defaultstate="collapsed" desc="开始时间 截止时间">
        if (!empty($params['begindate'])) {
            $begin_date = strtotime($params['begindate']);
        } else {
            $begin_date = '';
        }
        if (!empty($params['enddate'])) {
            $end_date = strtotime('+1 day', strtotime($params['enddate']));
        } else {
            $end_date = '';
        }

        if (!empty($begin_date) && !empty($end_date)) {
            $where['w.create_time'] = array('between', "{$begin_date},{$end_date}");
        } else if (!empty($begin_date) && empty($end_date)) {
            $where['w.create_time'] = array('egt', $begin_date);
        } else if (empty($begin_date) && !empty($end_date)) {
            $where['w.create_time'] = array('elt', $end_date);
        }
        // </editor-fold>

        $total=$model->alias('w')
            ->join('account a','a.id = w.account_id','left')
            ->where($where)->count(); //记录总数
        $page_size =$params['limit']; //获取分页数
        $start = $params['offset']; //获取开始的记录数
        //获取排序字段------------------------------------------------------------开始

        $sort_name = $params['sort'];
        $sort_desc = $params['order'];

        if (!empty($sort_name)) {
            $sort[$sort_name] = $sort_desc;
        } else {
            $sort['w.flag_status'] = 'desc'; //默认排序
        }
        //获取排序字段------------------------------------------------------------结束

        $rows = $model->alias('w')
            ->join('account a','a.id = w.account_id','left')
            ->field('w.*,a.name,a.mobile,a.wechat')
            ->where($where)
            ->limit($start, $page_size)
            ->order($sort)
            ->select();

        $array=array(
            'total'=>$total,
            'rows'=>$rows
        );

        return $array;
    }

    public function logic_verify($id){
        $model = new AccountWithdrawOrder();
        return $model->alias('w')
            ->join('account a','a.id = w.account_id','left')
            ->field('w.*,a.name,a.mobile')->where(['w.id'=>$id])->find();
    }

    public function logic_verify_submit($id){
        Db::startTrans();
        $model = new AccountWithdrawOrder();
        $item=$model->alias('w')
            ->join('account a','a.id = w.account_id','left')
            ->join('account_wechat aw','aw.account_id =a.id','left')
            ->field('w.*,a.name,a.mobile,aw.openid')->where(['w.id'=>$id])->find();
        $verify_money=$item['apply_money'];
        $update_data=array(
            'verify_time'=>time(),
            'verify_money'=>$verify_money,
            'flag_status'=>1
        );
        $res1=$model->where(['id'=>$id])->update($update_data);
        if(!$res1){
            Db::rollback();
            return array(
                'success'=>false,
                'message'=>'数据出错，请稍后再试1'
            );
        }

        $insert_data=array(
            'type'=>4,
            'account_id'=>$item['account_id'],
            'create_time'=>time(),
            'operation_id'=>cookie(Config::get('const.cookie_name_admin')),
            'object_id'=>$item['id']
        );
        $log_model=new AccountLog();
        $res2=$log_model->save($insert_data);
        if(!$res2){
            Db::rollback();
            return array(
                'success'=>false,
                'message'=>'数据出错，请稍后再试2'
            );
        }

        $pay=PayManagement::ent_instance();
        $params=array(
            'partner_trade_no'=>$item['order_sn'],
            'openid'=>$item['openid'],
            'amount'=>$verify_money*100,
            'desc'=>"用户提现",
            'spbill_create_ip'=>Request::instance()->ip(),
            'check_name'=>'NO_CHECK'
        );

       // $res_pay=$pay->transfers($params);
        $res_pay = [
            "return_code"=>"SUCCESS",
            "result_code"=>"SUCCESS"
        ];
      //todo 系统繁忙，请稍后再试。请使用原单号以及原请求参数重试，否则可能造成重复支付等资金风险
        if($res_pay==false){
            Db::rollback();
            return array(
                'success'=>false,
                'message'=>'数据出错，请稍后再试3'
            );
        }else{
            if($res_pay['return_code']=='SUCCESS' and $res_pay['result_code']=='SUCCESS'){//成功支付
                $update_finish=array(
                    'finish_time'=>$res_pay['payment_time'],
                    'finish_money'=>$verify_money,
                    'flag_status'=>3,
                    'trade_order_sn'=>$res_pay['payment_no']
                );
                $res3=$model->where(['id'=>$id])->update($update_finish);
                if(!$res3){
                    Db::rollback();
                    return array(
                        'success'=>false,
                        'message'=>'数据出错，请稍后再试4'
                    );
                }
                //插入钱帐记录
                $bill_model=new AccountBill();
                $data3=array(
                    ['account_id'=>$item['account_id'],'money'=>0-$verify_money,'remark'=>'提现'],
                );

                $res4=$bill_model->saveAll($data3);
                if(!$res4){
                    Db::rollback();
                    return array(
                        'success'=>false,
                        'message'=>'数据出错3，请稍后再试5'
                    );
                }
                //解冻余额
                $account_model=new Account();
                $res5=$account_model->where(['id'=>$item['id']])->setDec('frozen_money',$verify_money);
                if(!$res5){
                    Db::rollback();
                    return array(
                        'success'=>false,
                        'message'=>'数据出错3，请稍后再试6'
                    );
                }

            }else{
                Db::rollback();
                return array(
                    'success'=>false,
                    'message'=>'数据出错，请稍后再试7'
                );
            }

        }

        Db::commit();
        return array(
            'success'=>true,
            'message'=>'操作成功'
        );
    }

    public function pay($order){

    }

    public function logic_withdrawl_cancel($params){
        Db::startTrans();
        $model = new AccountWithdrawOrder();
        $wo_item=$model->where(['id'=>$params['id']])->find();
        $wo_data=array(
            'flag_status'=>3,
            'refuse_reason'=>$params['refuse_reason'],
            'verify_time'=>time()
        );
        $res1=$model->where(['id'=>$params['id']])->update($wo_data);
        if(!$res1){
            Db::rollback();
            return array(
                'success'=>false,
                'message'=>'数据出错，请稍后再试'
            );
        }
        $ac_model=new Account();
        $ac_item=$ac_model->where(['id'=>$wo_item['account_id']])->find();
        $ac_data=array(
            'money'=>$ac_item['money']+$wo_item['apply_money'],
            'frozen_money'=>$ac_item['frozen_money']-$wo_item['apply_money']
        );
        $res2=$ac_model->where(['id'=>$wo_item['account_id']])->update($ac_data);
        if(!$res2){
            Db::rollback();
            return array(
                'success'=>false,
                'message'=>'数据出错，请稍后再试'
            );
        }
        //todo 发送消息给客户
        Db::commit();
        return array(
            'success'=>true,
            'message'=>'操作成功'
        );
    }

}